package org.bright.service.Impl;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.bright.dao.AnimalDao;
import org.bright.entity.User;
import org.bright.service.AnimalService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class AnimalServiceImpl implements AnimalService {

    @Override
    public int insertInto(User user) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        AnimalDao animalDao = sqlSession.getMapper(AnimalDao.class);

        return animalDao.insertInto(user);
    }

    @Override
    public int updateUser(User user) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        AnimalDao animalDao = sqlSession.getMapper(AnimalDao.class);
        return animalDao.updateUser(user);
    }

    @Override
    public int deleteUser(int id) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        AnimalDao animalDao = sqlSession.getMapper(AnimalDao.class);
        return animalDao.deleteUser(id);
    }

    @Override
    public List<User> getUsers() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        AnimalDao animalDao = sqlSession.getMapper(AnimalDao.class);
        List<User> users = animalDao.getUsers();
        return users;
    }
}
